package scau.mis4.chanyulin.utils;

/**
 * Created by cyl on 2017/12/28.
 * 十六进制字符串工具类
 */
public class HexUtils {

    /**
     * 将十六进制字符串转换为字节
     * @param str
     * @return
     */
    public static byte toByte(String str) {
        return toBytes(str)[0];
    }

    /**
     * 将十六进制字符串转换为字节数组
     * @param str
     * @return
     */
    public static byte[] toBytes(String str) {
        if (str == null || str.trim().equals(""))
            return new byte[0];
        byte[] bytes = new byte[str.length() / 2];
        for (int i = 0; i < str.length() / 2; i++) {
            String subStr = str.substring(i * 2, i * 2 + 2);
            bytes[i] = (byte) Integer.parseInt(subStr, 16);
        }
        return bytes;
    }

    /**
     * 将字节转换为十六进制字符串
     * @param b
     * @return
     */
    public static String fromByte(byte b) {
        String hexStr = "";
        int v = b & 0xFF;
        String temp = Integer.toHexString(v);
        if (temp.length() < 2) hexStr = "0";
        hexStr += temp;
        return hexStr;
    }

}
